Learning To Create Your Own Custom Functions

Published

January 4, 2025

ABSTRACT
TBD.

1 Introduction

If you’re anything like me, when you first thought of creating your own custom functions in R it felt so wildly out of your comfort zone that you decided against it. They seemed big and scary, and only something the “really good” R coders did. The reality is far from that, and I hope this post does something to dissuade that fear and push you to start creating your own functions. Below, I’d like to discuss the essentials:

  • What are functions really?
  • Why you should consider making custom functions.
  • How you can make your own functions.
  • Some compelling reasons for making your own functions.
Note

Want to see one of my custom functions in action? I’ve already written an entire blog post about a function I use almost every day! Check it out here, it is all about cleaning and organizing dataframes (yes, I am aware that sounds boring, I promise its not).

2 Functionable Functions

Lets cut to chase, straight up what is a function? A function is just more code. When you use the function mean(), that’s just more code, the function mutate()? - more code, SuperAwesomeCustomFunctionXXY()? - just more code.

What do I mean by that? Well if you were to take a look inside the function and see what it is doing, you would see that in a lot of cases what it is doing is running extra R code. For instance if you run the following code in your R console:

Code
#load the required library for the function
library(flextable)

#run a function without the brackets to see what it is doing
add_body
function (x, top = TRUE, ..., values = NULL) 
{
    if (!inherits(x, "flextable")) {
        stop(sprintf("Function `%s` supports only flextable objects.", 
            "add_body()"))
    }
    new_data <- as_new_data(x = x, ..., values = values)
    x$body <- add_rows_to_tabpart(x$body, new_data, first = top)
    x
}
<bytecode: 0x000002319c925a18>
<environment: namespace:flextable>

You would receive an output that looks like this: (minus the highlighting of course).

Look closely at the orange section and you will see that it is actually R code! Look even closer and you will see that it is running its own functions!

Here, fixed that meme for you:

Note

A small side note, the code in a function is not always R code, but that doesn’t really matter for us.

So whats the take away here?

  • Takeaway 1: You are already using functions in your code every day.
  • Takeaway 2: Its all just code, and if you are reading this you probably already code, and if you already code you can write your own functions no sweat!

Jokes aside, if it is all just code, why have functions? Generally speaking, functions are written because the thing they are doing gets done a whole lot. For example, I have to take the mean of a bunch of numbers in my job more times that I can count, and if I had to write out the inner workings of the mean function every time, I’d pull my hair out more times that I can count.

Functions usually fill a specific niche, they do one thing really well, and nothing else. This also means that they are relatively simple, and if you felt like it you might even be able to dissect the function like we did above to see exactly how it works. (Although it is also perfectly fine to never worry about looking inside, don’t stress). In some cases you will encounter massive over complicated functions that do lots of seemingly unconnected things, but that is rarely true.

Functions that work well together, such as a whole heap of functions that work on tables, get bundled up together into “packages”. These is where the idea of “packages” comes from in R - you are just downloading a whole bunch of functions, which is just a whole bunch of code.

3 Making Your Own Functions

Okay its time to start talking about making your own functions. As we have covered, functions (particularly the ones you are going to write) are just R code. But obviously there is a little bit more to it than that. Lets look at the inside of a function again:

Overall, a function can be denoted as follows: your_function_name <- function(inputs){code} As we have covered, the orange part is the R code, that is the bit of code that gets executed when you use a function, and it goes inside the curly brackets. The dark green section at the top is the inputs section, where you tell the function what inputs to take, and what inputs are required. The light green section at the bottom, for our purposes we can ignore that, it is metadata about the function and where it comes from.

The function as denoted above, then needs to be assigned to an object using the <- symbol. This makes the function like any other object in R where we can call it up later from our global environment. Lets make our first function to understand this better.

Code
custom_function_1 <- function(x){print(x)}


custom_function_1(1)
[1] 1

What are functions?

  • they are bits of code that get reused lots
  • you are already using functions in R
  • functions often fill a specific niche, most of the time they do one thing really well, and nothing else
  • sometimes functions are super complex and can do a variety of things that don’t really seem connected
  • but alot of the time they are fairly simple
  • you can actually look inside functions if you want to

Why make your own

  • save time
  • better readability
  • … hang on this is sounding alot like for loops (side track, how are they different?)
  • flex on your friends
  • improve skill

Thanks For Reading!

Please stick around, and have a read of several of my other posts. You'll find work on everything from simple data management and organisation skills, all the way to writting custom functions, tackling complex environmental problems, and my journey when learning new environmental data analyst skills.


A work by Adam Shand. Reuse: CC-BY-NC-ND.

adamshand22@gmail.com


This work should be cited as:
Adam Shand, "[Insert Document Title]", "[Insert Year]".

Buy Me a Coffee!